package org.dreamwork.modbus.protocol;

public class PDU {
    /** 功能码 */
    public int function;

    /** 子功能 */
    public Integer subCode;

    /** 起始地址 */
    public Integer address;

    /** 请求个数 */
    public Integer count;

    /** 请求值 */
    public Integer value;

    /** 错误码 */
    public Integer error;

    /** 数据域 */
    public byte[] data;

    public byte[] toByteArray () {
        int pos = 1;
        byte[] buff = new byte[256];
        buff[0] = (byte) function;
        if (subCode != null) {
            buff[pos ++] = subCode.byteValue ();
        }
        if (error != null) {
            buff[pos ++] = error.byteValue ();
        }
        if (address != null) {
            buff[pos++] = (byte) (address >> 8);
            buff[pos++] = (byte) (address & 0xff);
        }
        if (count != null) {
            buff[pos++] = (byte) (count >> 8);
            buff[pos++] = (byte) (count & 0xff);
        }
        if (value != null) {
            buff[pos++] = (byte) (value >> 8);
            buff[pos++] = (byte) (value & 0xff);
        }
        if (data != null) {
            buff[pos ++] = (byte) data.length;  // 数据域长度
            System.arraycopy (data, 0, buff, pos, data.length);
            pos += data.length;
        }

        byte[] data = new byte[pos];
        System.arraycopy (buff, 0, data, 0, pos);
        return data;
    }
}